package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.mkt.PlotDetailDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.ProjectDomain;
import top.infopub.mgr.mkt.domain.SetupProDomain;
import top.infopub.mgr.mkt.jsonvo.SetupJsonVo;
import top.infopub.mgr.mkt.service.PreProjectService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.CollectProjectVo;
import top.infopub.mgr.mkt.vo.InvestmentInfoVo;
import top.infopub.mgr.mkt.vo.PlotInfoVo;
import top.infopub.mgr.mkt.vo.SetupProVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.mkt.*;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 立项管理
 * @author wangw
 * @version 2020年1月8日
 * @see SetupProjectController
 * @since
 */
@Controller
@RequestMapping("/setupPro")
public class SetupProjectController extends GenericFlowController {

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private PreProjectService preProjectService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    /**
     * 立项列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-setupPro-list";
    }

    /**
     * 立项列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ProjectDomain> queryDataByCondition(CollectProjectVo collectProjectVo, ParamPage paramPage)throws ParseException {
        Page<ProjectDomain> page = new Page<ProjectDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = setupProService.selectPageByDomainWhere(page, collectProjectVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 立项-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<SetupProDomain> queryMyCheckDataByCondition(SetupProVo setupProVo, ParamPage paramPage) {
        Page<SetupProDomain> page = new Page<SetupProDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (setupProVo.getEndDate() != null) {
            setupProVo.setEndDate(DateUtils.addDays(setupProVo.getEndDate(), 1));
        }
        setupProVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = setupProService.selectMyCheckByDomainWhere(page, setupProVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 立项-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可立项的立项记录
        List<PreProject> preProjects = preProjectService.selectUsableSetupPreProject();
        request.setAttribute("preProjects", preProjects);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-setupPro-add";
    }

    /**
     * 根据id查询立项详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 立项Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request,String id,String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        SetupPro setupPro = setupProService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        if (setupPro != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), setupPro.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), setupPro.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(setupPro.getProcessId()) && setupPro.getProcessId().length() > 10) {
                request.setAttribute("processId", setupPro.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(setupPro.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), setupPro.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-projectApproval-detail";
    }

    @RequestMapping("/querySetupDetail")
    @ResponseBody
    public RspVo querySetupDetail(String id) {
        //项目立项详情信息
        SetupJsonVo setupJson = setupProService.queryDetailById(id);
//        RspVo rspVo = RspVo.getSuccessResponse(setupJson);
        return RspVo.getSuccessResponse(setupJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request,String id, String processDealWith){
//        Map<String, Object> map = new HashMap<String, Object>();
//        SetupProVo setupPro = setupProService.selectById(id);
//        map.put("setupPro", setupPro);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, setupPro.getProcessId());
//        return new ModelAndView("mkt/lay-setupPro-detail", map);
//    }

    @RequestMapping("/toDetail")
    public String queryDetailById(HttpServletRequest request,String id, String processDealWith){
        SetupProVo setupPro = setupProService.selectById(id);
        request.setAttribute("setupPro", setupPro);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        request.setAttribute("edit", "edit");
        return "mkt/lay-setupPro-add";
    }

    /**
     * 立项-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        SetupProVo setupPro = setupProService.selectById(id);
        request.setAttribute("setupPro", setupPro);
        //查询可立项的立项记录
        List<PreProject> preProjects = preProjectService.selectUsableSetupPreProject();
        request.setAttribute("preProjects", preProjects);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-setupPro-copy";
    }

    /**
     * 新增立项
     * @return
     */
    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody RspVo save(HttpServletRequest request,SetupProVo setupPro) {
//        //判断项目是否已存在
//        List<SetupPro> setupPros = setupProService.selectByProCode(setupPro.getProCode());
//        if(CollectionUtils.isNotEmpty(setupPros)){
//            return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("项目【" + setupPro.getProName()
//                + "】已立项~");
//        }
//        String fromChannel = request.getParameter("fromChannel");//项目渠道
//        String linkPower = request.getParameter("linkPower");//居住地址
//        if(fromChannel.equals("2")){//居间合作
//            if(StringUtils.isEmpty(linkPower)){
//                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
//            }
//        }
//        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
//        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
//
//        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
//        String[] subName = request.getParameterValues("subName");//子项名称
//        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
//        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
//        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
//
//        String[] fileAtt11 = request.getParameterValues("fileAtt11");
//        String[] fileAtt12 = request.getParameterValues("fileAtt12");
//        String[] fileAtt13 = request.getParameterValues("fileAtt13");
//        String[] fileAtt14 = request.getParameterValues("fileAtt14");
//        String[] fileAtt15 = request.getParameterValues("fileAtt15");
//        String[] fileAtt16 = request.getParameterValues("fileAtt16");
//        String[] fileAtt19 = request.getParameterValues("fileAtt19");
//
//        if(sgCoopId != null && sgCoopId.length > 0){
//            for(int i=0; i< sgCoopId.length; i++){
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if(StringUtils.isNotEmpty(coopId)){
//                    if(StringUtils.isEmpty(coopeffect)){
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位作用未选择");
//                    }
//                }else{
//                    if(StringUtils.isNotEmpty(coopeffect)){
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位名称未选择");
//                    }
//                }
//            }
//        }
//
//        if(fileAtt11 == null || fileAtt11.length <1){
//            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("立项申请建议书未上传");
//        }
//        if(fileAtt12 == null || fileAtt12.length <1){
//            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("项目财政承受可行性评估未上传");
//        }
//        if(fileAtt13 == null || fileAtt13.length <1){
//            return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("项目物有所值评估未上传");
//        }
//
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//
//        /**
//         * 立项主表处理
//         */
//        String id = IdFactory.getUUIDUpper();
//        setupPro.setId(id);
//        setupPro.setHrStaffApplyId(vo.getHrStaffId());
//        setupPro.setHrOrgId(setupPro.getSetupOrgId());
//        setupPro.setHrDeptId(setupPro.getSetupDeptId());
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
//        setupPro.setStaffName(staffInfo.getStaffName());
//        setupPro.setAddBy(vo.getId());
//        setupPro.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("mkt_setup_pro_codes");
//        setupPro.setCodes(codes);
//        // 处理processId
//        setupPro.setProcessId(IdFactory.getUUIDUpper());
//        setupPro.setProcessStatus("1");//审批中
//        setupPro.setUptBy(vo.getId());
//        setupPro.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //合作单位处理
//        List<SetupProCoop> setupProCoops = new ArrayList<SetupProCoop>();
//        if(sgCoopId != null && sgCoopId.length > 0){
//            for(int i=0; i<sgCoopId.length; i++){
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if(StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)){
//                    continue;
//                }
//                String coopid = IdFactory.getUUIDUpper();//自动生成主键
//                SetupProCoop setupProCoop = new SetupProCoop();
//                setupProCoop.setId(coopid);
//                setupProCoop.setSetupProId(id);
//                setupProCoop.setSgCoopId(coopId);
//                setupProCoop.setCoopEffect(coopeffect);
//                setupProCoop.setAddBy(vo.getId());
//                setupProCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                setupProCoops.add(setupProCoop);
//            }
//
//        }
//
//        //子项处理
//        List<SetupProSub> setupProSubs = new ArrayList<SetupProSub>();
//        for(int i=0; i<orderIdx.length; i++){
//            String orderId = orderIdx[i];
//            SetupProSub setupProSub = new SetupProSub();
//            String subId = IdFactory.getUUIDUpper();//自动生成主键
//            setupProSub.setId(subId);
//            setupProSub.setSetupProId(id);
//            setupProSub.setOrderIdx(Integer.parseInt(orderId));
//            setupProSub.setSubName(subName[i]);
//            setupProSub.setWorkYears(new BigDecimal(subWorkYears[i]));
//            setupProSub.setBuildYears(new BigDecimal(subBuildYears[i]));
//            setupProSub.setOmYears(new BigDecimal(subOmYears[i]));
//            setupProSub.setAddBy(vo.getId());
//            setupProSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//            setupProSubs.add(setupProSub);
//        }
//        /**
//         * 上传的文件记录加入集合
//         */
//        List<SetupProAtt> fileAtts = new ArrayList<SetupProAtt>();
//        //立项申请建议书
//        if(fileAtt11 != null){
//            for(String file : fileAtt11){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目财政承受可行性评估
//        if(fileAtt12 != null){
//            for(String file : fileAtt12){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目物有所值评估
//        if(fileAtt13 != null){
//            for(String file : fileAtt13){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //营销策划书（选填）
//        if(fileAtt14 != null){
//            for(String file : fileAtt14){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目实施方案（选填）
//        if(fileAtt15 != null){
//            for(String file : fileAtt15){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //营销经理责任书（选填）
//        if(fileAtt16 != null){
//            for(String file : fileAtt16){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //其他资料（选填）
//        if(fileAtt19 != null){
//            for(String file : fileAtt19){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        setupProService.addSetupPro(setupPro, setupProCoops, setupProSubs, fileAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "立项 -新增立项：项目名="+setupPro.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

//    /**
//     * 编辑立项
//     * @param request
//     * @param setupPro
//     * @return
//     */
//    @RequestMapping("/edit")
//    public @ResponseBody RspVo edit(HttpServletRequest request,SetupProVo setupPro) {
//        String submitType = request.getParameter("submitType");//2=提交  1保存
//
//        String fromChannel = request.getParameter("fromChannel");//项目渠道
//        String linkPower = request.getParameter("linkPower");//居住地址
//        if("2".equals(fromChannel)){//居间合作
//            if(StringUtils.isEmpty(linkPower)){
//                return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("居间方不能为空");
//            }
//        }
//        String[] sgCoopId = request.getParameterValues("sgCoopId");//单位名称
//        String[] coopEffect = request.getParameterValues("coopEffect");//单位作用
//
//        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
//        String[] subName = request.getParameterValues("subName");//子项名称
//        String[] subWorkYears = request.getParameterValues("subWorkYears");//子项-合作周期（年）
//        String[] subBuildYears = request.getParameterValues("subBuildYears");//子项-建设周期（年）
//        String[] subOmYears = request.getParameterValues("subOmYears");//子项-运营周期（年）
//
//        String[] fileAtt11 = request.getParameterValues("fileAtt11");
//        String[] fileAtt12 = request.getParameterValues("fileAtt12");
//        String[] fileAtt13 = request.getParameterValues("fileAtt13");
//        String[] fileAtt14 = request.getParameterValues("fileAtt14");
//        String[] fileAtt15 = request.getParameterValues("fileAtt15");
//        String[] fileAtt16 = request.getParameterValues("fileAtt16");
//        String[] fileAtt19 = request.getParameterValues("fileAtt19");
//
//        if(sgCoopId != null && sgCoopId.length > 0){
//            for(int i=0; i< sgCoopId.length; i++){
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if(StringUtils.isNotEmpty(coopId)){
//                    if(StringUtils.isEmpty(coopeffect)){
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位作用未选择");
//                    }
//                }else{
//                    if(StringUtils.isNotEmpty(coopeffect)){
//                        return ErrorCodeEnum.ERROR_COMMON_CHECK.getRspVo("联合体单位-单位名称未选择");
//                    }
//                }
//            }
//        }
//
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//
//        /**
//         * 立项主表处理
//         */
//        String id = setupPro.getId();
//        setupPro.setUptBy(vo.getId());
//        setupPro.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //合作单位处理
//        List<SetupProCoop> setupProCoops = new ArrayList<SetupProCoop>();
//        if(sgCoopId != null && sgCoopId.length > 0){
//            for(int i=0; i<sgCoopId.length; i++){
//                String coopId = sgCoopId[i];
//                String coopeffect = coopEffect[i];
//                if(StringUtils.isEmpty(coopId) && StringUtils.isEmpty(coopeffect)){
//                    continue;
//                }
//                String coopid = IdFactory.getUUIDUpper();//自动生成主键
//                SetupProCoop setupProCoop = new SetupProCoop();
//                setupProCoop.setId(coopid);
//                setupProCoop.setSetupProId(id);
//                setupProCoop.setSgCoopId(coopId);
//                setupProCoop.setCoopEffect(coopeffect);
//                setupProCoop.setAddBy(vo.getId());
//                setupProCoop.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                setupProCoops.add(setupProCoop);
//            }
//
//        }
//
//        //子项处理
//        List<SetupProSub> setupProSubs = new ArrayList<SetupProSub>();
//        for(int i=0; i<orderIdx.length; i++){
//            String orderId = orderIdx[i];
//            SetupProSub setupProSub = new SetupProSub();
//            String subId = IdFactory.getUUIDUpper();//自动生成主键
//            setupProSub.setId(subId);
//            setupProSub.setSetupProId(id);
//            setupProSub.setOrderIdx(Integer.parseInt(orderId));
//            setupProSub.setSubName(subName[i]);
//            setupProSub.setWorkYears(new BigDecimal(subWorkYears[i]));
//            setupProSub.setBuildYears(new BigDecimal(subBuildYears[i]));
//            setupProSub.setOmYears(new BigDecimal(subOmYears[i]));
//            setupProSub.setAddBy(vo.getId());
//            setupProSub.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//            setupProSubs.add(setupProSub);
//        }
//        /**
//         * 上传的文件记录加入集合
//         */
//        List<SetupProAtt> fileAtts = new ArrayList<SetupProAtt>();
//        //立项申请建议书
//        if(fileAtt11 != null){
//            for(String file : fileAtt11){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目财政承受可行性评估
//        if(fileAtt12 != null){
//            for(String file : fileAtt12){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目物有所值评估
//        if(fileAtt13 != null){
//            for(String file : fileAtt13){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //营销策划书（选填）
//        if(fileAtt14 != null){
//            for(String file : fileAtt14){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //项目实施方案（选填）
//        if(fileAtt15 != null){
//            for(String file : fileAtt15){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //营销经理责任书（选填）
//        if(fileAtt16 != null){
//            for(String file : fileAtt16){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        //其他资料（选填）
//        if(fileAtt19 != null){
//            for(String file : fileAtt19){
//                SetupProAtt setupProAtt = createFileAtt(vo, id, file);
//                fileAtts.add(setupProAtt);
//            }
//        }
//        setupProService.editSetupPro(setupPro, setupProCoops, setupProSubs, fileAtts, submitType);
////        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "立项 -新增立项：项目名="+setupPro.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

    /**
     * 编辑立项
     * @param request
     * @param setupPro
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        SetupJsonVo setupJson = JSON.parseObject(str, SetupJsonVo.class);
        PlotDetailDto plotDetail = setupJson.getInfo();
        //更新项目基础信息表-MKT_PROJECT_INFO
        ProjectInfo proInfo = new ProjectInfo();
        BeanUtils.copyProperties(plotDetail, proInfo);

        //更新立项表-MKT_SETUP_PRO
        SetupPro setupPro = new SetupPro();
        setupPro.setGovAccess(plotDetail.getGovAccess());
        setupPro.setUptBy(vo.getId());
        setupPro.setUptTime(new Date());
        setupPro.setId(plotDetail.getId());

        //更新项目合作方-MKT_AFTER_SUMMARY_COOP
        List<AfterSummaryCoop> summCoopList = new ArrayList<>();
        if (setupJson.getSummaryCoops()!=null && setupJson.getSummaryCoops().size()>0){
            summCoopList = setupJson.getSummaryCoops();
            for (AfterSummaryCoop asc : summCoopList) {
                asc.setId(null);
                asc.setProCode(plotDetail.getProCode());
                asc.setAddBy(vo.getId());
                asc.setAddTime(new Date());
            }
        }
        //更新项目子项表格信息-MKT_PROJECT_SUB_INFO
        ProjectSubInfo proSubInfo = new ProjectSubInfo();
        proSubInfo.setProCode(plotDetail.getProCode());
        if (setupJson.getItemName() != null && setupJson.getItemName().size() > 0) {
            proSubInfo.setTitleJson(JSON.toJSONString(setupJson.getItemName()));
        }
        if (setupJson.getInvestmentInfoVos() != null && setupJson.getInvestmentInfoVos().size() > 0) {
            proSubInfo.setContentJson(JSON.toJSONString(setupJson.getInvestmentInfoVos()));
            StringBuffer rowTotal = new StringBuffer();
            StringBuffer colTotal = new StringBuffer();
            int itivIdx = 0;
            int itivSize = setupJson.getInvestmentInfoVos().size();
            for (InvestmentInfoVo itiv : setupJson.getInvestmentInfoVos()) {
                if (itivIdx == (itivSize - 1)) {
                    for (BigDecimal tmpTotal : itiv.getList()) {
                        rowTotal.append(tmpTotal.toString());
                        rowTotal.append(",");
                    }
                    rowTotal.append(itiv.getTotal());
                }
                if (itivIdx > 2) {
                    colTotal.append(itiv.getTotal());
                    colTotal.append(",");
                }
                itivIdx++;
            }
            if (colTotal.length() > 0) colTotal.deleteCharAt(colTotal.length() - 1);
            proSubInfo.setRowTotal(rowTotal.toString());
            proSubInfo.setColTotal(colTotal.toString());
        }
        proSubInfo.setUptBy(vo.getId());
        proSubInfo.setUptTime(new Date());

        //更新项目风险信息-MKT_PROJECT_RISK
        List<ProjectRisk> riskList = setupJson.getRiskTable();
        if(riskList!=null&&riskList.size()>0){
            for (ProjectRisk pr : riskList) {
                pr.setAddBy(vo.getId());
                pr.setAddTime(new Date());
                pr.setProCode(plotDetail.getProCode());
                pr.setRiskDesc(pr.getRiskDesc() != null ? pr.getRiskDesc() : "");
                pr.setRiskLevel(pr.getRiskLevel() != null ? pr.getRiskLevel() : "");
                pr.setSolveWay(pr.getSolveWay() != null ? pr.getSolveWay() : "");
                pr.setLatestProgress(pr.getLatestProgress() != null ? pr.getLatestProgress() : "");
                pr.setStatus(pr.getStatus() != null ? pr.getStatus() : "");
                pr.setUpdateBy(vo.getId());
                pr.setUpdateTime(new Date());
                pr.setRiskStage(ProProcessDetailTypeEnum.PRO_NODE_TYPE2.getNode());
            }
        }
        //更新立项策划信息-MKT_PLOT_INFO
        PlotInfoVo piv = setupJson.getPlotInfo();
        PlotInfo plotInfo = new PlotInfo();
        plotInfo.setProCode(plotDetail.getProCode());
        plotInfo.setCsResult(piv.getCsResult());
        plotInfo.setOptRemark(piv.getOptRemark());
        plotInfo.setCsBoundJson(JSON.toJSONString(piv.getPlotTableDatas()));
        plotInfo.setAddBy(vo.getId());
        plotInfo.setAddTime(new Date());

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(setupJson.getFileAtt()!=null){
            String[] fileAtt = setupJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, plotDetail.getProCode(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = setupProService.editSetupProDetail(proInfo, setupPro, summCoopList, proSubInfo, riskList, plotInfo, attachmentList, submitType, vo);
        return rspVo;
    }

//    /**
//     * 根据id查询立项记录
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getSetupProById")
//    @ResponseBody
//    public Map<String, Object> getSetupProById(String id) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        try {
//            SetupProVo setupProVo = setupProService.selectById(id);
//            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//            setupProVo.setStaffName(staffInfo.getStaffName());
//            map.put("setupPro", setupProVo);
//        }
//        catch (Exception e) {
//            log.error("查询立项记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if(StringUtils.isEmpty(types)){
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "setupProAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types+"|"+file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
